package com.ideal.frame.sys.service;

import com.ideal.frame.jpa.JpaRepositoryImpl;
import com.ideal.frame.sys.entity.QSysLevelMenu;
import com.ideal.frame.sys.entity.SysLevelMenu;
import com.ideal.frame.sys.entity.SysMenu;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: zhangdelei
 * @date: 2021/9/14-11:11 上午
 * @Description:
 **/
@Slf4j
@Service
public class SysLevelMenuService {

    @PersistenceContext
    protected EntityManager entityManager;

    private JpaRepositoryImpl<SysLevelMenu, Long> levelRepo;
    private QSysLevelMenu qSysLevelMenu = QSysLevelMenu.sysLevelMenu;

    @PostConstruct
    public void init() {
        this.levelRepo = new JpaRepositoryImpl<>(SysLevelMenu.class, entityManager);
    }

    /**
     * 根据级别获取菜单列表
     *
     * @param level
     * @return
     */
    public List<Long> getLevel(long level) {
        List<SysLevelMenu> levelMenus = levelRepo.selectFrom(qSysLevelMenu).where(qSysLevelMenu.level.eq(level)).fetch();
        return levelMenus != null ? levelMenus.stream().map(t -> t.getSysMenu().getId()).collect(Collectors.toList()) : Collections.emptyList();
    }

    /**
     * 获取菜单级别列表
     *
     * @param menuId
     * @return
     */
    public List<Long> getMenuLevel(long menuId) {
        List<SysLevelMenu> levelMenus = levelRepo.selectFrom(qSysLevelMenu).where(qSysLevelMenu.sysMenu.id.eq(menuId)).fetch();
        return levelMenus != null ? levelMenus.stream().map(t -> t.getLevel()).collect(Collectors.toList()) : Collections.emptyList();
    }

    /**
     * 批量保存级别根菜单的关联关系
     *
     * @param levels
     * @param menuId
     */
    @Transactional(rollbackFor = Exception.class)
    public void batchSave(List<Long> levels, long menuId) {
        levelRepo.delete(qSysLevelMenu).where(qSysLevelMenu.sysMenu.id.eq(menuId)).execute();
        List<SysLevelMenu> datas = levels.stream()
                .map(t -> {
                    SysMenu menu = new SysMenu();
                    menu.setId(menuId);
                    return SysLevelMenu.builder().level(t).sysMenu(menu).build();
                })
                .collect(Collectors.toList());
        levelRepo.saveAll(datas);
    }
}
